import { Component, ElementRef, ViewChild } from '@angular/core';

interface ITodo {
  id: number;
  content: string;
  completed: boolean;
}

//根组件配置
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  //声明数据
  public todoText: string = '';
  public todoData: Array<ITodo> = [];

  @ViewChild('title') //获取定义了`#title`的节点元素
  public oTitle: ElementRef | null = null;

  ngAfterViewInit() {
    setTimeout(() => {
      this.oTitle!.nativeElement.innerText = '待办事项';
    }, 1000);
  }

  //声明操作数据的方法
  public addTodo(): void {
    if (!this.todoText.length) return;
    const todo: ITodo = {
      id: new Date().getTime(),
      content: this.todoText,
      completed: false,
    };
    this.todoData.push(todo);
    this.todoText = '';
  }

  public toggleTodo(id: number): void {
    this.todoData = this.todoData.map((todo) => {
      if (todo.id === id) {
        todo.completed = !todo.completed;
      }
      return todo;
    });
  }

  public removeTodo(id: number): void {
    this.todoData = this.todoData.filter((todo) => todo.id !== id);
  }
}
